import pymysql
from copy import copy


class LotteryNumber:
    connection = None
    user = 'root'
    password = ''
    db_name = 'cqssc'
    host = 'localhost'
    cursor = None
    column_map = {'zero': 1, 'one': 1, 'two': 1, 'three': 1,
                  'four': 1, 'five': 1, 'six': 1, 'seven': 1,
                  'eight': 1, 'night': 1
                  }
    column_key_map = tuple()

    def __init__(self):
        self.connection = pymysql.connect(self.host, self.user, self.password, self.db_name)
        self.cursor = self.connection.cursor()
        self.column_key_map = tuple(self.column_map.keys())

    """
        判断是否有这个开奖数据
    """
    def hasPeriod(self, period):
        self.cursor = self.connection.cursor(cursor=pymysql.cursors.DictCursor)
        has_period_sql = r"select * from lottery_number where period = %s"
        self.cursor.execute(has_period_sql, (period,))
        result = self.cursor.fetchone()

        if result is None:
            return False
        else:
            return result

    def merage(self,period,column_map):
        period = period.split("-")
        number = int(period[1]) - 1

        if number > 0:
            period[1] = str(number).zfill(3)

        pre_period = "-".join(period)
        pre_data = self.hasPeriod(pre_period)

        if pre_data:
            for key,item in pre_data.items():
                if key in column_map:
                    column_map[key] += item

        return column_map


    def insertLottery(self, lottery_data):
        column_map = copy(self.column_map)
        column_map = self.merage(lottery_data['period'],column_map)
        column_map['period'] = lottery_data['period']
        column_map['number'] = lottery_data['number']
        numbers = tuple(int(num) for num in column_map['number'] if num.isdigit())

        for num in numbers:
            if num < len(self.column_key_map):
                key_transform = self.column_key_map[num]
                column_map[key_transform] = 0

        sql_values = tuple(column_map.values())
        insert_sql = r"insert into lottery_number(`zero`,`one`,`two`,`three`,`four`,`five`,`six`," \
                     r"`seven`,`eight`,`night`,`period`,`number`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        try:
            self.cursor.execute(insert_sql,args=sql_values)
            self.connection.commit()
            del column_map
            return self.cursor.lastrowid
        except Exception as e:
                self.connection.rollback()
                print(e)
                return False

    def close(self):
        self.cursor.close()
        self.connection.close()


if __name__ == "__main__":
    ln = LotteryNumber()
    ln.insertLottery({"period":"170604-002","number":"12345"})
